<?php
namespace backend\models;

use Yii;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;
date_default_timezone_set("PRC");

class MovieCollege extends ActiveRecord implements IdentityInterface
{
    const STATUS_DELETED = 0;
    const STATUS_ACTIVE = 10;
    const STATUS = 1;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%movie_college}}';
    }

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            TimestampBehavior::className(),
        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['title', 'describe','sort','banner','video'], 'trim'],
            [['title', 'describe','sort','banner','video'], 'required','message' => '{attribute}不能为空'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'title' => '标题',
            'describe' => '简介',
            'sort' => '排序',
            'banner' => '封面图',
            'video' => '视频',
        ];
    }

    public function scenarios()
    {
        return [
            'default' => [
                'title',
                'describe',
                'sort',
                'banner',
                'video',
            ],
            'create' => [
                'id',
                'title',
                'describe',
                'sort',
                'banner',
                'video',
                'admin_id',
                'admin_name'.
                'status',
                'create_time',
                'update_time',
                'deleted_at',
            ],
            'update' => [
                '!id',
                'title',
                'describe',
                'sort',
                'banner',
                'video',
                'admin_id',
                'admin_name'.
                'status',
                'create_time',
                'update_time',
                'deleted_at',
            ],
        ];
    }

    public static function deleteData($id){
        $model = static::findOne(['id' => $id]);
        if(empty($model)){
            return true;
        }
        $model->deleted_at = time();
        return $model->save();
    }

    /**
     * 更新数据
     * @author hey_heyang(635870453@qq.com)
     */
    public static function saveInfo($scenario, $data, $id = 0){
        if (!in_array($scenario, ['create', 'update'])) {
            return false;
        }
        $t = static::getDb()->beginTransaction();
        try {
            if ($scenario == 'update') {
                $id = intval($id);
                if (!$id) {
                    return false;
                }
                $model           = static::findOne(['id' =>$id]);
                if(empty($model)) throw new Exception('不存在此用户');
                $model->scenario = 'update';
            } else {
                $model           = new self();
                $model->scenario = 'create';
            }
            $model->setAttributes($data, false);
            if (!$model->save()) {
                $t->rollBack();
                return $model;
            }
            $model->refresh();
            $t->commit();
            return $model;
        } catch (Exception $e) {
            $t->rollback();
            return $e;
        }
    }

    /**
     * @inheritdoc
     */
    public static function selectData($params)
    {
        $query = new \yii\db\Query();
        $query->select(['*'])->from('movie_college');
        $query->where(['deleted_at' => null]);
        $query->orderBy([
            'sort' => SORT_ASC,
            'created_at' => SORT_DESC,
        ]);
        if(!empty($params['data'])){
            $query->andWhere(['like', 'title', $params['data']]);
        }
        $command = $query->createCommand();
        $result = $command->queryAll();
        foreach ($result as $k => $v){
            $result[$k]['admin'] = $v['admin_name'].'/'.$v['admin_id'];
            $result[$k]['created_at'] = date('Y-m-d H:i:s',$v['created_at']);
        }
        //var_dump($query->createCommand()->getRawSql());exit;
        return $result;
    }

    /**
     * @inheritdoc
     */
    public static function findAllData($data,$page = 1,$pageSize = 10)
    {
        $query = new \yii\db\Query();
        $query->select(['*'])->from('movie_college');
        $query->where(['deleted_at' => null]);
        $query->orderBy([
            //new \yii\db\Expression('FIELD (card_status, 1, 4, 3, 2)'),
            'sort' => SORT_DESC,
            'created_at' => SORT_DESC,
        ]);
        if(!empty($data)){
            $query->andWhere(['admin_id' => $data]);
            $query->orWhere(['like', 'admin_name', $data]);
            $query->orWhere(['like', 'title', $data]);
            $query->orWhere(['like', 'describe', $data]);
        }
        $page = $page ? $page : 1;
        $pageSize = $pageSize ? $pageSize : 10;
        $query->offset(($page - 1) * $pageSize)->limit($pageSize);
        $command = $query->createCommand();
        $result = $command->queryAll();
        //var_dump($query->createCommand()->getRawSql());exit;
        return $result;
    }

    /**
     * @inheritdoc
     */
    public static function findOneData($id)
    {
        $query = new \yii\db\Query();
        $query->select(['*'])->from('movie_college');
        $query->where(['deleted_at' => null]);
        $query->andWhere(['id' => $id]);
        $command = $query->createCommand();
        $result = $command->queryOne();
        //var_dump($query->createCommand()->getRawSql());exit;
        return $result;
    }

    /**
     * @inheritdoc
     */
    public static function findOneDataField($id,$field = '')
    {
        $query = new \yii\db\Query();
        $query->select($field)->from('movie_college');
        $query->where(['deleted_at' => null]);
        $query->andWhere(['id' => $id]);

        $command = $query->createCommand();
        $result = $command->queryOne();
        //var_dump($query->createCommand()->getRawSql());exit;
        return $result;
    }

    /**
     * @inheritdoc
     */
    public static function findIdentity($id)
    {
        return static::findOne(['id' => $id, 'status' => self::STATUS]);
    }

    /**
     * @inheritdoc
     */
    public static function findDataByUsername($username)
    {
        return static::findOne(['username' => $username, 'status' => self::STATUS]);
    }

    /**
     * @inheritdoc
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
    }

    /**
     * Finds user by username
     *
     * @param string $username
     * @return static|null
     */
    public static function findByUsername($username)
    {
        return static::findOne(['username' => $username, 'status' => self::STATUS_ACTIVE]);
    }

    /**
     * Finds user by password reset token
     *
     * @param string $token password reset token
     * @return static|null
     */
    public static function findByPasswordResetToken($token)
    {
        if (!static::isPasswordResetTokenValid($token)) {
            return null;
        }

        return static::findOne([
            'password_reset_token' => $token,
            'status' => self::STATUS_ACTIVE,
        ]);
    }

    /**
     * Finds out if password reset token is valid
     *
     * @param string $token password reset token
     * @return bool
     */
    public static function isPasswordResetTokenValid($token)
    {
        if (empty($token)) {
            return false;
        }

        $timestamp = (int) substr($token, strrpos($token, '_') + 1);
        $expire = Yii::$app->params['user.passwordResetTokenExpire'];
        return $timestamp + $expire >= time();
    }

    /**
     * @inheritdoc
     */
    public function getId()
    {
        return $this->getPrimaryKey();
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey()
    {
        return $this->auth_key;
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
    }

    /**
     * Validates password
     *
     * @param string $password password to validate
     * @return bool if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        return Yii::$app->security->validatePassword($password, $this->password_hash);
    }

    /**
     * Generates password hash from password and sets it to the model
     *
     * @param string $password
     */
    public function setPassword($password)
    {
        $this->password_hash = Yii::$app->security->generatePasswordHash($password);
    }

    /**
     * Generates "remember me" authentication key
     */
    public function generateAuthKey()
    {
        $this->auth_key = Yii::$app->security->generateRandomString();
    }

    /**
     * Generates new password reset token
     */
    public function generatePasswordResetToken()
    {
        $this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
    }

    /**
     * Removes password reset token
     */
    public function removePasswordResetToken()
    {
        $this->password_reset_token = null;
    }
}
